﻿using Abp.Configuration.Startup;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.MultiTenancy;
using Abp.Runtime;
using Abp.Runtime.Caching;
using Abp.Runtime.Session;
using Abp.Threading;
using AbpProjectTemplate.Domain.Users;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;

namespace AbpProjectTemplate.Components.Runtime
{
    public class AppSession : ClaimsAbpSession
    {
        private readonly IUserCache _userCache;
        public AppSession(
            IPrincipalAccessor principalAccessor,
            IMultiTenancyConfig multiTenancy,
            ITenantResolver tenantResolver,
            IAmbientScopeProvider<SessionOverride> sessionOverrideScopeProvider,
            IUserCache userCache)
            : base(
                  principalAccessor,
                  multiTenancy,
                  tenantResolver,
                  sessionOverrideScopeProvider)
        {
            this._userCache = userCache;
        }

        /// <summary>
        /// 获取当前登录用户信息(缓存)
        /// </summary>
        public User GetUser()
        {
            if (!this.UserId.HasValue)
                return null;

            return this._userCache.Get(this.UserId.Value);
        }

        /// <summary>
        /// 获取当前登录用户信息(缓存)
        /// </summary>
        public async Task<User> GetUserAsync()
        {
            if (!base.UserId.HasValue)
                return null;

            return await this._userCache.GetAsync(this.UserId.Value);
        }

        /// <summary>
        /// 获取当前实例
        /// </summary>
        public static AppSession Instance
        {
            get { return IocManager.Instance.Resolve<AppSession>(); }
        }
    }
}

